<?php

namespace App\Http\Controllers\User;

use App\Exceptions\ExceptionHelper;
use App\Exceptions\ExceptionSms;
use App\Models\User;
use App\Models\WechatAuth;
use App\Services\Common\UserService;

/**
 * 登录
 * Class LoginController
 * @package App\Http\Controllers\User
 */
class LoginController extends CommonController
{
    public function getWxOpenid()
    {
        ExceptionSms::checkParams($this->input(), [
            'code' => 'required'
        ]);

        $code = $this->input('code');

        if (!is_lisa()) {
            $auth        = \Wechat::getUserAuthInfo($code);
            $openid      = $auth['openid'];
            $unionid     = $auth['unionid'];
            $session_key = $auth['session_key'];
            WechatAuth::storeAuth($session_key, $openid, $unionid);

            $data = [
                'openid' => $openid,
            ];
        } else {
            $openid      = \Str::random(50);
            $unionid     = \Str::random(50);
            $session_key = \Str::random(50);
            WechatAuth::storeAuth($session_key, $openid, $unionid);
            $data = [
                'openid' => $openid
            ];
        }
        return ExceptionSms::returnSuccess($data);
    }

    public function wxLogin()
    {
        ExceptionSms::checkParams($this->input(), [
            'openid'        => 'required',
            'iv'            => 'required',
            'encryptedData' => 'required',
        ]);
        $openid        = $this->input('openid') ?? ""; // 因为小程序绑定了公众号，因此传的参数是unionid
        $iv            = $this->input('iv') ?? "";
        $encryptedData = $this->input('encryptedData') ?? "";
        /** @var WechatAuth $auth */
        $auth = WechatAuth::getOneByOpenid($openid);
        if (!$auth) ExceptionSms::returnError('openid无效');

        $session_key = $auth->session_key;
        if (!is_lisa()) {
            $auth_info = \Wechat::decryptData($session_key, $encryptedData, $iv); // 解析用户信息
            if (!$auth_info) ExceptionSms::returnError('用户信息解析失败');
        } else {
            $auth_info = [
                'unionId'   => $auth['unionid'],
                'nickName'  => User::getDefaultNickName(),
                'avatarUrl' => User::getDefaultAvatar(),
                'gender'    => '2',
                'province'  => '上海',
                'city'      => '上海市',
                'country'   => '中国',
            ];
        }


        $auth = $auth->storeUserInfo($auth_info);

        $user = User::getOneByOpenid($auth->openid);
        if ($user) {
            if ($user->isLock()) {
                throw ExceptionHelper::getInstance(ExceptionHelper::USER_IS_LOCK);
            }
            $data = UserService::setLogin($user);
        } else {
            $user = UserService::storeWechatAuth($openid, $auth);
            $data = UserService::setLogin($user);
        }
        return ExceptionSms::returnSuccess($data);
    }


}
